package com.design.composite.config;

import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.design.composite.repository.DictRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

import static com.alibaba.fastjson.serializer.SerializerFeature.*;


@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private DictRepository dictRepository;

    /**
     * json序列化
     *
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig converterConfig = new FastJsonConfig();
        converterConfig.setSerializerFeatures(
                PrettyFormat,
                WriteNullListAsEmpty,
                WriteNullStringAsEmpty,
                WriteMapNullValue);
        converter.setFastJsonConfig(converterConfig);
        converters.add(converter);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/index.html");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String material = dictRepository.findByCode("MATERIAL").getPath();
        String preview = dictRepository.findByCode("PREVIEW").getPath();
        String random = dictRepository.findByCode("RANDOM").getPath();
        registry.addResourceHandler("/files/**").addResourceLocations("file:" + material);
        registry.addResourceHandler("/pFiles/**").addResourceLocations("file:" + preview);
        registry.addResourceHandler("/rFiles/**").addResourceLocations("file:" + random);
    }
}
